﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using FileStorage.Caching;

namespace FileStorage.Comparing.Comparers.Contents
{
    /// <summary>
    /// Compares two data identifiers by calculating the MD5 hash
    /// of both identifiers
    /// </summary>
    public class Md5ContentsComparer : IDataIdentifierComparer
    {
        #region IDataIdentifierComparer Members

        public Guid GetHash(string fileStorageName, ICacheContainer cacheContainer, Guid dataIdentifier)
        {
            Guid result;

            byte[] bytes = FileStorageCacherFacade.GetBytesData(fileStorageName, dataIdentifier, cacheContainer);
            List<byte> hashBytes = CalculateMD5Hash(bytes).ToList().Take(16).ToList();
            while (hashBytes.Count < 16)
            {
                hashBytes.Add(0);
            }
            result = new Guid(hashBytes.ToArray());

            return result;
        }

        #endregion

        private static byte[] CalculateMD5Hash(byte[] inputBytes)
        {
            // step 1, calculate MD5 hash from input
            MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] hash = md5.ComputeHash(inputBytes);

            return hash;
        }
    }
}
